package com.xiongwei.io;

import java.awt.im.InputSubset;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Java标准库的java.io.InputStream定义了所有输入流的超类：
 *
 * FileInputStream实现了文件流输入；
 *
 * ByteArrayInputStream在内存中模拟一个字节流输入。
 *
 * 总是使用try(resource)来保证InputStream正确关闭。
 *
 * @author XiongWei
 * @date 2021/1/7
 */
public class InputStreamUse {

    public static void main(String[] args) {
        InputStreamUse isu = new InputStreamUse();
        //isu.testJDK7try();
        //isu.testBufferInputStream();
        isu.testByteArrayInputStream();
    }

    /**
     * JDK7新的try(resource)语法
     */
    public void testJDK7try() {
        //编译器会自动为我们写入finally并调用close()
        try(InputStream is = new FileInputStream("src/com/xiongwei/io/readme.txt")) {
            int n;
            while ((n = is.read()) != -1) {
                System.out.print((char) n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 利用缓冲区一次读取多个字节
     */
    public void testBufferInputStream() {
        try (InputStream is= new FileInputStream("src/com/xiongwei/io/readme.txt")) {
            byte[] bb = new byte[1000];
            int n;
            while ((n = is.read(bb)) != -1) {
                System.out.println("read " + n + "bytes.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ByteArrayInputStream在内存模拟字节流输入
     */
    public void testByteArrayInputStream() {
        byte[] b = {23,24};
        try (InputStream is = new ByteArrayInputStream(b)) {
            int n;
            while ((n = is.read()) != -1) {
                System.out.println((byte) n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
